package com.example.sulei.rootchangerinfo.utils;

import android.os.Environment;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Created by hp on 2017/4/16.
 */

public class PermissionsUtils {

    /**
     * 应用程序运行命令获取 Root权限，设备必须已破解(获得ROOT权限)
     *
     * @return 应用程序是/否获取Root权限
     */
    public static boolean upgradeRootPermission(String pkgCodePath) {
        java.lang.Process process = null;
        DataOutputStream os = null;
        try {
            String cmd = "chmod 777 " + pkgCodePath;
            process = Runtime.getRuntime().exec("su"); //切换到root帐号
            os = new DataOutputStream(process.getOutputStream());
            os.writeBytes(cmd + "\n");
            os.writeBytes("exit\n");
            os.flush();
            process.waitFor();
        } catch (Exception e) {
            return false;
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                process.destroy();
            } catch (Exception e) {
            }
        }
        return true;
    }


    /**
     * 获取Android系统build.prop文件
     */
    public static void getBuild_prop() {

        BufferedReader reader = null;
        File sdDir;
        if (isSdcard()) {
            //获取SD卡根目录
            sdDir = Environment.getExternalStorageDirectory();
        } else {
            return;
        }

        //build.prop文件路径
        String propPath = "/system";
        //遍历该文件夹找到build.prop文件
        File file = new File(propPath);
        if (file.exists() && file.isDirectory()) {
            System.out.println("MainActivity.getBuild_prop  进入systems文件夹");
            try {
                String line = null;
                StringBuffer buffer = new StringBuffer();
                reader = new BufferedReader(new FileReader(new File(propPath + "/build.prop")));
                System.out.println("MainActivity.getBuild_prop  进入build.prop文件");
                while ((line = reader.readLine()) != null) {
                    buffer.append(line + "\n");
                }
                System.out.println("MainActivity.getBuild_prop" + buffer.toString());

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } else {
            System.out.println("MainActivity.getBuild_prop  文件夹不存在！！！！！！！！！！！！");
        }
    }

    /**
     * 判断SD卡是否存在
     */
    private static boolean isSdcard() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            System.out.println("SD卡不存在");
            return false;
        }
    }

    /**
     * 获取build.prop文件内容
     */
    public static void get_build_prop() {
        //build.prop文件路径
        String propPath = "/system/build.prop";
        File file = new File(propPath);
        if (file.exists()) {
            System.out.println("build.prop配置文件存在...");      //得到文件流
            BufferedReader reader = null;      //以行为单位，将字符串放入数组
            String[] array = null;      //原始配置信息字符串
            String originalContent = null;
            try {
                reader = new BufferedReader(new FileReader(file));
                StringBuilder sb = new StringBuilder();
                String str = null;
                while ((str = reader.readLine()) != null) {
                    sb.append(str + "\n");
                }
                originalContent = sb.toString();
                reader.close();
                System.out.println("读取原始配置信息成功...");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
            //以换行符为分隔 返回字符串数组
            array = originalContent.split("\n");
            for (int i = 0; i < array.length; i++) {
                if (array[i].contains("ro.product.model")) {
                    array[i] = "ro.product.model=iPhone7";
                } else if (array[i].contains("ro.product.brand")) {
                    array[i] = " ro.product.brand=Xiaom";
                }
            }
            BufferedWriter writer = null;
            try {
                StringBuilder sBuilder = new StringBuilder();
                for (int i = 0; i < array.length; i++) {
                    sBuilder.append(array[i] + "\n");
                }
                String finalMsg = sBuilder.toString();
                System.out.println("######################");

//                fos = new FileOutputStream(file);
//                writer = new BufferedWriter(new OutputStreamWriter(fos));
                final String newpath = String.valueOf(Environment.getExternalStorageDirectory());
                File file1 = new File(newpath + "/build.prop");//创建新的文件存储修改后的内容
                if (!file1.exists()) {
                    file1.createNewFile();
                    writer = new BufferedWriter(new FileWriter(file1));
                    writer.append(finalMsg);
                    System.out.println("MainActivity.test" + finalMsg);
                    writer.flush();
                    writer.close();
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                getPermissions(newpath);
                                //对build.prop文件修改权限
//                                    changerPermissions();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();

                } else {
                    //copy到system目录下
                    System.out.println("MainActivity.test======" + "cp " + newpath + "/build.txt /system/1.txt");
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                getPermissions(newpath);
                                //对build.prop文件修改权限
//                                    changerPermissions();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();

                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("build.prop file is not exist");
        }
    }

    private static void getPermissions(String newpath) throws IOException {
        java.lang.Process su = Runtime.getRuntime().exec("su");
        DataOutputStream dos = new DataOutputStream(su.getOutputStream());
        BufferedReader reader = new BufferedReader(new InputStreamReader(su.getInputStream()));
        String line = null;

        try {
//            dos.writeBytes("chmod 777 /sdcard/build.prop\n");
            dos.writeBytes("mount -o remount rw /system/\n");
            dos.writeBytes("cp /system/build.prop /system/build.prop_bak\n");
            dos.writeBytes("cp /sdcard/build.prop /system/build.prop\n");

//            dos.writeBytes("cp" + newpath + "/build.txt /system/1.txt\n");
            dos.flush();
            su.waitFor();
            System.out.println("MainActivity.getPermissions" + reader.readLine());
            if ((line = reader.readLine()) != null) {
                System.out.println("MainActivity.getPermissions====" + line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            try {
                if (dos != null) {
                    dos.close();
                }
                if (reader != null) {
                    reader.close();
                }
                su.destroy();
            } catch (Exception e) {
            }
        }
    }

}
